package com.cnplan.controller;

import com.cnplan.core.Constant;
import com.cnplan.core.Result;
import com.cnplan.core.ResultGenerator;
import com.cnplan.entity.SystemRole;
import com.cnplan.entity.SystemUser;
import com.cnplan.service.AuthService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by Administrator on 2018/4/25.
 */
@Controller(value = "HomeController")
@RequestMapping("/")
public class HomeController {

    @Autowired
    private AuthService authService;

    @RequestMapping(value = {"/","/index"})
    public String index() {
        return "index";
    }

    @RequestMapping(value ="/login")
    public String login(HttpServletRequest request, HttpServletResponse response){
        return "login";
    }

    @RequestMapping(value="/proxy")
    public String proxy(){
        return "proxy";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result loginPost(@RequestParam(value = "username", required = true) String userName,
                            @RequestParam(value = "password", required = true) String password,
                            @RequestParam(value = "rememberMe", required = true, defaultValue = "false") boolean rememberMe,
                            ServletRequest request){

        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(new UsernamePasswordToken(userName, password, rememberMe));

            // 获取当前用户
            SystemUser temp = new SystemUser();
            temp.setUserName(userName);
            SystemUser user = authService.getSystemUser(temp);
            ((HttpServletRequest) request).getSession().setAttribute(Constant.CURRENT_USER, user);
            ((HttpServletRequest) request).getSession().setAttribute(Constant.CURRENT_USERNAME, user.getUserName());
            ((HttpServletRequest) request).getSession().setAttribute(Constant.CURRENT_USER_ID, user.getId());

            // 判断当前用户是否有管理员权限
            List<SystemRole> userRoleList = authService.listRoleByUserId(user.getId());
            String hasAdminRole = "false";
            for(SystemRole role : userRoleList){
                if("administrator".equals(role.getRoleName())){
                    hasAdminRole = "true";
                }
            }
            ((HttpServletRequest) request).getSession().setAttribute(Constant.HAS_ADMIN_ROLE, hasAdminRole);

            subject.getSession().setTimeout(-1000l);
            return ResultGenerator.genSuccessResult();
        } catch (AuthenticationException e) {
            e.printStackTrace();
            String err = "org.apache.shiro.authc.UnknownAccountException";
            if (err.equals(e.toString())){
                return ResultGenerator.genFailResult("您的账号已被锁定，请联系管理员");
            }
            return ResultGenerator.genFailResult("您的账号或密码输入错误");
        }
    }

    @RequestMapping(value = "/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

    @RequestMapping(value = "/todo")
    public String todo(HttpServletRequest request){
        return "todo";
    }

    @RequestMapping("/unauthorized")
    public String unauthorized(HttpServletRequest request) {
        return "unauthorized";
    }

    @RequestMapping(value = {"/error"})
    public String error(HttpServletRequest request) {
        return "error";
    }
}
